import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:citiesocial/beans/user_entity.dart';
import 'dart:async';

class Configs {
  static const Configs _singleton = const Configs._internal();
  const Configs._internal();
  factory Configs() => _singleton;

  ///接口地址
  static const url = 'http://citiesocial.zadtek.com/interface.php';

  ///由于initState方法不能马上调用接口，所以需要一个延迟
  static const loadDelay = const Duration(milliseconds: 500);

  ///全局背景色
  static const background = const Color(0xFFECF0F1);

  ///全局分割线颜色
  static const lineColor = const Color(0xFFdddddd);

  ///主色调，绿
  static const main = const Color(0xFF00B16A);

  ///分割线高度
  static const lineHeight = 0.5;

  ///分割线
  static const dividerLine = const Divider(
    height: Configs.lineHeight,
    color: Configs.lineColor,
  );

  ///绿色的分割线
  static const dividerMainColor = const Divider(
    height: Configs.lineHeight,
    color: Configs.main,
  );

  ///保存的key值
  static const _userIdKey = '_user_id_',
      _userTokenKey = '_user_token_',
      _emailKey = '_email_',
      _cartCountKey = '_cart_count_';
  static String _userId, _userToken, _email;
  static int _cartCount = 0;

  ///获取用户信息，仅在应用初始化时运行一次即可
  static void initUserState() async {
    final user = await SharedPreferences.getInstance();
    _userId = user.getString(_userIdKey);
    _userToken = user.getString(_userTokenKey);
    _email = user.getString(_emailKey);
    _cartCount = user.getInt(_cartCountKey);
  }

  ///保存用户信息
  static void saveUserState(UserEntity user) async {
    final userInfo = await SharedPreferences.getInstance();
    _userId = user?.user_id;
    _userToken = user?.user_token;
    _email = user?.email;
    userInfo.setString(_userIdKey, _userId);
    userInfo.setString(_userTokenKey, _userToken);
    userInfo.setString(_emailKey, _email);
  }

  ///判断用户是否已经登录，并在未登录时跳转登录界面
  static Future<bool> mayLogin(BuildContext context) async {
    if (isLogined) {
      return true;
    } else {
      final one = await Navigator.pushNamed(context, '/login');
      return '1' == one;
    }
  }

  ///保存购物车中到数量
  static void saveCartCount(int cartCount) async {
    final userInfo = await SharedPreferences.getInstance();
    _cartCount = cartCount;
    userInfo.setInt(_cartCountKey, cartCount);
  }

  ///用户id，非null
  static String get userId => _userId ?? '';

  ///是否已经登录
  static bool get isLogined =>
      _userId != null &&
      _userId.isNotEmpty &&
      _userToken != null &&
      _userToken.isNotEmpty;

  ///用户token，非null
  static String get userToken => _userToken ?? '';

  ///email
  static String get email => _email ?? '';

  ///购物车数量
  static int get cartCount => _cartCount ?? 0;

  ///拼接接口地址，只需要传后半部分即可，即m=之后的内容
  static String getUrl(String fun) {
    debugPrint('$url?m=$fun');
    return Uri.encodeFull('$url?m=$fun');
  }
}
